<?php
    if(isset($_SERVER['HTTP_REFERER'])) {
        $refer = $_SERVER['HTTP_REFERER'];
        $domain = parse_url($refer, PHP_URL_HOST);
        
        mysql_connect('localhost', 'root', '12345');
        mysql_select_db('counter');
        // Получить или создать id_site
        $query = "SELECT * FROM sites WHERE domain = '$domain'";
        $res = mysql_query($query);
        if(mysql_num_rows($res) > 0) {
            $row = mysql_fetch_array($res);
            $id_site = $row['id'];
        } else {
            $query = "INSERT INTO sites(domain) VALUES('$domain');";
            mysql_query($query);
            $id_site = mysql_insert_id();
        }

        // Получить или создать id_user
        if(isset($_COOKIE['counter'])) {
            $cookie = $_COOKIE['counter'];
            $query = "SELECT * FROM users WHERE cookie = '$cookie'";
            $res = mysql_query($query);
            if(mysql_num_rows($res) > 0) {
                $row = mysql_fetch_array($res);
                $id_user = $row['id'];
            }
        }

        if(!isset($id_user) || ($id_user == 0)) {
            $cookie = sha1($_SERVER['HTTP_USER_AGENT'].$_SERVER['HTTP_ACCEPT_LANGUAGE'].time());
            $query = "INSERT INTO users(cookie) VALUES('$cookie')";
            mysql_query($query);
            $id_user = mysql_insert_id();
            setcookie("counter", $cookie, time() + 60*60*24*30*12*10);
        }
        
        // Зафиксировать визит
        $page = parse_url($refer, PHP_URL_PATH);
        $query = "INSERT INTO visits(id_site, id_user, time, page) 
                        VALUES($id_site, $id_user,now(),'$page')";
        mysql_query($query);

        // Получить количество загрузок страницы
        $query = "SELECT COUNT(*) FROM visits WHERE id_site = $id_site";

        $res = mysql_query($query);
        $row = mysql_fetch_array($res);
        $clicks = (int)$row[0];

        // Получить количество посетителей
        $query = "SELECT COUNT(*) FROM users WHERE id IN 
                        (SELECT id_user FROM visits WHERE id_site = $id_site)";
        $res = mysql_query($query);
        $row = mysql_fetch_array($res);
        $visitors = (int)$row[0];

        header('Content-Type: image/png');
        // Нарисовать картинку
        $img = imagecreate(200, 50);
        
        $bgcolor = imagecolorallocate($img, 200, 200, 200);
       
        imagefill($img, 10, 10, $bgcolor);  

        $txtcolor = imagecolorallocate($img, 255, 0, 0);

        imagestring($img, 5, 10, 10, "Clicks:  $clicks", $txtcolor);
        imagestring($img, 5, 10, 30, "Visitors:$visitors", $txtcolor);
        
        imagepng($img);  
    }
